﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using System.Data;
using JKF.Entities.Model;
using JKF.BusinessLayer;

namespace JKF.HandlerLayer.Stock
{
    public partial class Stock_OutHandler:AHttpHandler
    {
        private static bllSTOCK_OUT bllStock_Out = new bllSTOCK_OUT();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }
        /// <summary>
        /// 产品/耗材出库
        /// </summary> 
        public void InsertStock_Out()
        {
            try
            {
                var strScr = P("moduleObj");
                var clientObj = JsonSerializer.Deserialize<Stock_OutTemp>(strScr);
                var productInfo = this.BuildStock_OutinfoByJson(clientObj, false);
                bool reslt =  bllStock_Out.TransationSql(BuildStock_Out_InsertSqlByModel(productInfo));
                //写日志
                AppendLog(productInfo, null, LogType.Add);
                // 执行出库时，需要同步更新dbo.STOCK_AMOUNT 表中记录 
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Message = "出库成功.",
                        Data = new { OUT_KEY = productInfo.OUT_KEY, OUT_NO = productInfo.OUT_NO, USER_NAME = bllSYS_USER.CurrentUser.REAL_NAME },
                        Success =reslt
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        
        /// <summary>
        /// 产品/耗材出库编辑
        /// </summary>
        public void EditStock_Out()
        {
            try
            {
                var strScr = P("moduleObj");
                var clientObj = JsonSerializer.Deserialize<Stock_OutTemp>(strScr);
                var productInfo = this.BuildStock_OutinfoByJson(clientObj, true);
                // 修改出库时，(暂时保留，以便后续用)需要同步更新dbo.STOCK_AMOUNT 表中记录 
                string stock_amount_update_sql = string.Format(" update dbo.STOCK_AMOUNT set PRODUCT_NUMS=PRODUCT_NUMS-{0}+{1} where PRODUCT_KEY='{2}' and SHOP_CODE='{3}' ;", productInfo.PRODUCT_NUMS, productInfo.OLD_PRODUCT_NUMS, productInfo.PRODUCT_KEY, productInfo.SHOP_CODE);
                string stock_out_update_sql = string.Format(" update dbo.STOCK_OUT set PRODUCT_NUMS={0},DATE_OUT='{1}',MEMO='{2}',DATE_UPDATE='{3}' where OUT_KEY='{4}'", productInfo.PRODUCT_NUMS, productInfo.DATE_OUT, productInfo.MEMO, productInfo.DATE_UPDATE, productInfo.OUT_KEY);
                //先获取原来实体
                var serverObj = bllStock_Out.GetModel(productInfo.OUT_KEY);
                //修改
                bool reslt = bllStock_Out.TransationSql(stock_out_update_sql + stock_amount_update_sql);
                
                //写日志
                AppendLog(BuildStock_OutTemp(serverObj), productInfo, LogType.Edit);
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Message = "修改成功.",
                        Data = new { OUT_KEY = productInfo.OUT_KEY, OUT_NO = productInfo.OUT_NO, USER_NAME = bllSYS_USER.CurrentUser.REAL_NAME },
                        Success = reslt
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 获取每个店铺的出库列表数据
        /// </summary>
        public void GetSTOCK_OUTS()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
            if (P("isExport") == "1")
            {//出库单号	产品类别	产品名称	出库数量	备注	出库日期

                DataTable dt = bllStock_Out.GetStock_OutsBLL(P("NAME"), bllSYS_USER.CurrentUser.SHOP_CODE, P("PRODUCT_KEY"), P("PRODUCT_NUMS"), P("OUT_NO"), P("REAL_NAME"), P("MEMO"), P("DATA_START"), P("DATA_END"), P("PageIndex").ToInt32(), -1, ref pageCount, ref rowCount);

                IDictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("OUT_NO", "出库单号");
                columns.Add("SORT_NAME", "产品类别");
                columns.Add("NAME", "产品名称");
                columns.Add("PRODUCT_NUMS", "出库数量");
                columns.Add("MEMO", "备注");
                columns.Add("DATE_OUT", "出库日期");
                Excel.Export("产品出库记录", dt, columns, Response, Excel.PageType.handler); 
            }
            else
            {
                //从视图中获取：123
                obj.Entity = from a in bllStock_Out.GetStock_OutsBLL(P("NAME"), bllSYS_USER.CurrentUser.SHOP_CODE, P("PRODUCT_KEY"), P("PRODUCT_NUMS"), P("OUT_NO"), P("REAL_NAME"), P("MEMO"), P("DATA_START"), P("DATA_END"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                             select new
                             {
                                 OUT_KEY = a.Field<Guid>("OUT_KEY"),
                                 OUT_NO = a.Field<string>("OUT_NO"), //出库单号
                                 SORT_NAME = a.Field<string>("SORT_NAME"), //产品类别名称
                                 NAME = a.Field<string>("NAME"), //产品名称
                                 PRODUCT_NUMS = a.Field<int>("PRODUCT_NUMS"), //出库数量
                                 MEMO = a.Field<string>("MEMO"), //备注
                                 USER_CREATE = a.Field<string>("USER_CREATE"), //操作员姓名
                                 DATE_CREATE = (a.Field<DateTime>("DATE_CREATE")).ToString("yyyy-MM-dd"),
                                 DATE_OUT = (a.Field<DateTime>("DATE_OUT")).ToString("yyyy-MM-dd HH:mm:ss")
                             };

                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
        }
        
        /// <summary>
        /// 根据出库主键获取出库记录
        /// </summary>
        public void GetStock_OutByCode()
        {
            try
            {
                var scid = P("moduleKey");
                var stock_out_model = bllStock_Out.GetModel(new Guid(scid));
                var stock_out_product_model = new bllPRODUCT().GetModel(stock_out_model.PRODUCT_KEY);
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Data = stock_out_model,
                        Mode = new { SORT_KEY = stock_out_product_model.SORT_KEY, TYPE = stock_out_product_model.TYPE },
                        FormatString = stock_out_model.DATE_OUT.ToString("yyyy-MM-dd HH:mm:ss")
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 根据主键OUT_KEY删除出库记录，采用逻辑删除
        /// </summary>
        public void DeleteSTOCK_OUT()
        {
            try
            {
                var out_key = P("id");
                //1.逻辑删除出库记录，
                string stock_out_delete_sql = string.Format("update dbo.STOCK_OUT set STATUS=9 where OUT_KEY='{0}'", out_key);
                STOCK_OUTinfo model = bllStock_Out.GetModel(new Guid(out_key));
                //2. 更新逻辑删除出库记录产品的库存信息
                string update_stock_amount_sql = string.Format("  update dbo.STOCK_AMOUNT set PRODUCT_NUMS=PRODUCT_NUMS+{0},  DATE_UPDATE='{1}' where PRODUCT_KEY='{2}'", model.PRODUCT_NUMS, DateTime.Now.ToString(), model.PRODUCT_KEY.ToString());
                bool reslt = bllStock_Out.TransationSql(stock_out_delete_sql+update_stock_amount_sql);
                //写日志
                AppendLog(BuildStock_OutTemp(model), null, LogType.Delete);
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Success =reslt , Data = out_key }));

            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 从Json对象构建对象
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="isEdit">是否为编辑</param>
        /// <returns></returns>
        public Stock_OutTemp BuildStock_OutinfoByJson(Stock_OutTemp stock_out_info, bool isEdit)
        {
            var entity = new Stock_OutTemp();
            if (!isEdit) // 添加
            {
                entity.OUT_KEY = new Guid(DB.GetNewGuid(DB.HR)); //Guid.NewGuid();
                entity.OUT_NO = this.BuildStock_Out_NO(bllSYS_USER.CurrentUser.SHOP_CODE);//这个需要算法来自动生成
            }
            else // 修改
            {
                entity.OUT_KEY = stock_out_info.OUT_KEY;
                entity.OUT_NO = stock_out_info.OUT_NO;
            }

            entity.MEMO = stock_out_info.MEMO;
            entity.PRODUCT_KEY = stock_out_info.PRODUCT_KEY;
            entity.PRODUCT_NUMS = stock_out_info.PRODUCT_NUMS;
            entity.OLD_PRODUCT_NUMS = stock_out_info.OLD_PRODUCT_NUMS;
            entity.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE; //当前用户店面编码
            entity.DATE_OUT = stock_out_info.DATE_OUT;
            entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY; // 获取当前用户guid
            entity.DATE_CREATE = System.DateTime.Now.ToString();
            entity.DATE_UPDATE = System.DateTime.Now.ToString();
            return entity;
        }
        
        /// <summary>
        /// 通过实体来构成插入语句
        /// </summary>
        /// <param name="stock_in_temp"></param>
        /// <returns></returns>
        public string BuildStock_Out_InsertSqlByModel(Stock_OutTemp stock_out_temp)
        {//OUT_KEY, PRODUCT_KEY, OUT_NO, PRODUCT_NUMS, DATE_OUT, MEMO, STATUS, SHOP_CODE, USER_CREATE, DATE_CREATE, DATE_UPDATE
            string stock_amount_sql = string.Empty;
            string stock_out_sql = string.Format("insert into dbo.STOCK_OUT(OUT_KEY, PRODUCT_KEY, OUT_NO, PRODUCT_NUMS, DATE_OUT, MEMO, SHOP_CODE, USER_CREATE, DATE_CREATE, DATE_UPDATE, STATUS) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','1');", stock_out_temp.OUT_KEY, stock_out_temp.PRODUCT_KEY, stock_out_temp.OUT_NO, stock_out_temp.PRODUCT_NUMS, stock_out_temp.DATE_OUT, stock_out_temp.MEMO, stock_out_temp.SHOP_CODE,stock_out_temp.USER_CREATE,stock_out_temp.DATE_CREATE,stock_out_temp.DATE_UPDATE);
            //1.先判断出库的产品dbo.STOCK_AMOUNT表中是否存在(product_key,shop_code)，如果存在则更新
            if (new bllSTOCK_AMOUNT().Exists(stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE))
            {
                stock_amount_sql = string.Format(" update dbo.STOCK_AMOUNT set PRODUCT_NUMS=PRODUCT_NUMS-{0}+{1} where PRODUCT_KEY='{2}' and SHOP_CODE='{3}'", stock_out_temp.PRODUCT_NUMS, stock_out_temp.OLD_PRODUCT_NUMS, stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE);
            }
            else
            {
                stock_amount_sql = string.Format(" insert into dbo.STOCK_AMOUNT(PRODUCT_KEY, SHOP_CODE, PRODUCT_NUMS, USER_CREATE, DATE_CREATE, DATE_UPDATE) VALUES('{0}','{1}','-{2}','{3}','{4}','{5}')", stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE, stock_out_temp.PRODUCT_NUMS, stock_out_temp.USER_CREATE, stock_out_temp.DATE_CREATE, stock_out_temp.DATE_UPDATE);
            }
            return stock_out_sql + stock_amount_sql;
        } 
        /// <summary>
        /// 生成出库单号
        /// </summary>
        /// <returns></returns>
        public string BuildStock_Out_NO(string shop_code)
        {
            return bllStock_Out.GetStock_OUT_NOBLL(shop_code);
        }

        /// <summary>
        /// 组装实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private Stock_OutTemp BuildStock_OutTemp(STOCK_OUTinfo model)
        {
            var temp = new Stock_OutTemp();
            temp.DATE_CREATE = model.DATE_CREATE.ToString();
            temp.DATE_OUT = model.DATE_OUT.ToString();
            temp.DATE_UPDATE = model.DATE_UPDATE.ToString();
            temp.OUT_KEY = model.OUT_KEY;
            temp.OUT_NO = model.OUT_NO;
            temp.MEMO = model.MEMO;
            temp.PRODUCT_KEY = model.PRODUCT_KEY;
            temp.PRODUCT_NUMS = model.PRODUCT_NUMS.ToString();
            return temp;
        }
         
        /// <summary>
        /// 此类专用于前台传值从JSON对象构成实体对象
        /// </summary>
        public class Stock_OutTemp
        {
            /// <summary>
            /// 主键，出库表
            /// </summary>
            public Guid OUT_KEY { get; set; }
            /// <summary>
            /// 产品ID
            /// </summary>
            public Guid PRODUCT_KEY { get; set; }
            /// <summary>
            /// 出库单号
            /// </summary>
            public string OUT_NO { get; set; }
            /// <summary>
            /// 出库数量（新）
            /// </summary>
            public string PRODUCT_NUMS { get; set; }
            /// <summary>
            /// 出库数量（旧）
            /// </summary>
            public string OLD_PRODUCT_NUMS { get; set; }
            /// <summary>
            /// 出库日期
            /// </summary>
            public string DATE_OUT { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string MEMO { get; set; }
            /// <summary>
            /// 店铺
            /// </summary>
            public string SHOP_CODE { get; set; }
            /// <summary>
            /// 创建者ID
            /// </summary>
            public Guid USER_CREATE { get; set; }
            /// <summary>
            /// 创建日期
            /// </summary>
            public string DATE_CREATE { get; set; }
            /// <summary>
            /// 修改日期
            /// </summary>
            public string DATE_UPDATE { get; set; }
        }

        #region Log
        /// <summary>
        /// 添加出库部分日志
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="logType">操作类型</param>
        private void AppendLog(Stock_OutTemp from, Stock_OutTemp to, LogType logType)
        {
            StringBuilder builder = new StringBuilder();
            if (logType == LogType.Add)
            {
                bllSYS_LOG.SaveLog(SysConfig.STOCK_OUT_MODULE_CODE,
                    SysConfig.STOCK_OUT,
                    from.OUT_KEY.ToString(),
                    string.Format("添加出库记录，出库单号：\"{0}\"产品key：\"{1}\"  出库数量：\"{2}\"  ", from.OUT_NO, from.PRODUCT_KEY.ToString(), from.PRODUCT_NUMS),
                    SysConfig.Add,
                    BusinessBase.ClientIp);
                return;
            }
            if (logType == LogType.Edit)
            {

                builder.AppendFormat("修改出库记录，出库单号：\"{0}\"  产品key：\"{1}\"  出库数量：\"{2}\"", from.OUT_NO, from.PRODUCT_KEY.ToString(), from.PRODUCT_NUMS);
                var bChange = false;
                if (from.DATE_OUT != to.DATE_OUT)
                {
                    builder.AppendFormat("出库日期 原值：\"{0}\"，现值：\"{1}\"", from.DATE_OUT.ToString(), to.DATE_OUT.ToString());
                    bChange = true;
                }
                if (from.PRODUCT_NUMS != to.PRODUCT_NUMS)
                {
                    builder.AppendFormat("出库数量 原值：\"{0}\"，现值：\"{1}\"", from.PRODUCT_NUMS, to.PRODUCT_NUMS);
                    bChange = true;
                }
                if (from.MEMO != to.MEMO)
                {
                    builder.AppendFormat("备注  原值:\"{0}\"，现值:\"{1}\"", from.MEMO, to.MEMO);
                    bChange = true;
                }
                if (bChange)
                {
                    bllSYS_LOG.SaveLog(SysConfig.STOCK_OUT_MODULE_CODE,
                      SysConfig.STOCK_OUT,
                      from.OUT_KEY.ToString(),
                      builder.ToString(),
                      SysConfig.Edit,
                      BusinessBase.ClientIp);
                }
                return;
            }
            if (logType == LogType.Delete)
            {
                bllSYS_LOG.SaveLog(SysConfig.STOCK_OUT_MODULE_CODE,
                      SysConfig.STOCK_OUT,
                      from.OUT_KEY.ToString(),
                      string.Format("删除出库记录，出库单号：\"{0}\"  产品key：\"{1}\"  出库数量：\"{2}\"", from.OUT_NO, from.PRODUCT_KEY.ToString(), from.PRODUCT_NUMS),
                      SysConfig.Delete,
                      BusinessBase.ClientIp);
            }
        }
        #endregion
    }
}
